package handler

import (
	"database/sql"
	"encoding/json"
	"errors"
	"fmt"
	"net/http"
	"strconv"
	"strings"

	"github.com/yourusername/apijson-auth/middleware"
	"github.com/yourusername/apijson-auth/model"
)

type Handler struct {
	DB *sql.DB
}

// 通用响应结构
type Response struct {
	Code    int         `json:"code"`
	Message string      `json:"message"`
	Data    interface{} `json:"data,omitempty"`
}

// Get 处理 GET 请求
func (h *Handler) Get(w http.ResponseWriter, r *http.Request) {
	// 从上下文获取用户
	user := r.Context().Value("user").(model.User)

	// 解析请求参数
	table := r.URL.Query().Get("table")
	if table == "" {
		respondWithError(w, http.StatusBadRequest, "Table name is required")
		return
	}

	idStr := r.URL.Query().Get("id")
	columns := r.URL.Query().Get("columns")
	conditions := r.URL.Query().Get("conditions")

	// 验证表级权限
	verifier := middleware.APIJSONVerifier{}
	if !verifier.Verify(table, "GET", user.Role) {
		respondWithError(w, http.StatusForbidden, "Insufficient permissions")
		return
	}

	// 构建查询
	var query string
	var args []interface{}

	// 处理列选择
	selectColumns := "*"
	if columns != "" {
		selectColumns = strings.ReplaceAll(columns, ",", ", ")
	}

	// 基础查询
	query = fmt.Sprintf("SELECT %s FROM %s", selectColumns, table)

	// 处理ID查询
	if idStr != "" {
		query += " WHERE id = ?"
		args = append(args, idStr)
	} else if conditions != "" {
		// 处理自定义条件
		query += " WHERE " + conditions
	}

	// 添加行级权限控制
	switch table {
	case "User":
		if user.Role < model.ADMIN {
			if strings.Contains(query, "WHERE") {
				query += " AND "
			} else {
				query += " WHERE "
			}
			query += "id = ?"
			args = append(args, user.ID)
		}
	case "Article":
		if user.Role < model.ADMIN {
			if strings.Contains(query, "WHERE") {
				query += " AND "
			} else {
				query += " WHERE "
			}
			query += "(user_id = ? OR status = 'published')"
			args = append(args, user.ID)
		}
	}

	// 执行查询
	rows, err := h.DB.Query(query, args...)
	if err != nil {
		respondWithError(w, http.StatusInternalServerError, err.Error())
		return
	}
	defer rows.Close()

	// 获取列名
	columnNames, err := rows.Columns()
	if err != nil {
		respondWithError(w, http.StatusInternalServerError, err.Error())
		return
	}

	// 处理结果集
	var results []map[string]interface{}
	for rows.Next() {
		// 创建值的切片
		values := make([]interface{}, len(columnNames))
		valuePtrs := make([]interface{}, len(columnNames))
		for i := range columnNames {
			valuePtrs[i] = &values[i]
		}

		// 扫描行数据
		if err := rows.Scan(valuePtrs...); err != nil {
			respondWithError(w, http.StatusInternalServerError, err.Error())
			return
		}

		// 构建结果map
		entry := make(map[string]interface{})
		for i, col := range columnNames {
			val := values[i]
			b, ok := val.([]byte)
			if ok {
				entry[col] = string(b)
			} else {
				entry[col] = val
			}
		}
		results = append(results, entry)
	}

	// 处理单条结果
	if idStr != "" && len(results) == 1 {
		respondWithJSON(w, http.StatusOK, Response{
			Code:    http.StatusOK,
			Message: "success",
			Data:    results,
		})
		return
	}

	respondWithJSON(w, http.StatusOK, Response{
		Code:    http.StatusOK,
		Message: "success",
		Data:    results,
	})
}

// Post 处理 POST 请求
func (h *Handler) Post(w http.ResponseWriter, r *http.Request) {
	// 从上下文获取用户
	user := r.Context().Value("user").(model.User)

	// 解析请求体
	var requestBody map[string]interface{}
	if err := json.NewDecoder(r.Body).Decode(&requestBody); err != nil {
		respondWithError(w, http.StatusBadRequest, "Invalid request body")
		return
	}

	// 获取表名
	table, ok := requestBody["table"].(string)
	if !ok || table == "" {
		respondWithError(w, http.StatusBadRequest, "Table name is required")
		return
	}

	// 验证表级权限
	verifier := middleware.APIJSONVerifier{}
	if !verifier.Verify(table, "POST", user.Role) {
		respondWithError(w, http.StatusForbidden, "Insufficient permissions")
		return
	}

	// 处理不同表的插入逻辑
	var result sql.Result
	var err error

	switch table {
	case "User":
		if user.Role < model.ADMIN {
			respondWithError(w, http.StatusForbidden, "Only admin can create users")
			return
		}
		result, err = h.insertUser(requestBody)
	case "Article":
		result, err = h.insertArticle(user.ID, requestBody)
	default:
		respondWithError(w, http.StatusBadRequest, "Unsupported table")
		return
	}

	if err != nil {
		respondWithError(w, http.StatusInternalServerError, err.Error())
		return
	}

	// 获取插入ID
	id, err := result.LastInsertId()
	if err != nil {
		respondWithError(w, http.StatusInternalServerError, err.Error())
		return
	}

	respondWithJSON(w, http.StatusCreated, Response{
		Code:    http.StatusCreated,
		Message: "created",
		Data:    map[string]int64{"id": id},
	})
}

// insertUser 处理用户插入
func (h *Handler) insertUser(data map[string]interface{}) (sql.Result, error) {
	name, ok := data["name"].(string)
	if !ok || name == "" {
		return nil, errors.New("name is required")
	}

	roleStr, ok := data["role"].(string)
	if !ok {
		roleStr = "LOGIN"
	}
	role := model.UNKNOWN
	switch strings.ToUpper(roleStr) {
	case "ADMIN":
		role = model.ADMIN
	case "OWNER":
		role = model.OWNER
	case "CIRCLE":
		role = model.CIRCLE
	case "CONTACT":
		role = model.CONTACT
	case "LOGIN":
		role = model.LOGIN
	}

	query := "INSERT INTO User(name, role) VALUES(?, ?)"
	return h.DB.Exec(query, name, role)
}

// insertArticle 处理文章插入
func (h *Handler) insertArticle(userID int, data map[string]interface{}) (sql.Result, error) {
	title, ok := data["title"].(string)
	if !ok || title == "" {
		return nil, errors.New("title is required")
	}

	content, ok := data["content"].(string)
	if !ok || content == "" {
		return nil, errors.New("content is required")
	}

	status := "draft"
	if s, ok := data["status"].(string); ok {
		status = s
	}

	query := "INSERT INTO Article(title, content, status, user_id) VALUES(?, ?, ?, ?)"
	return h.DB.Exec(query, title, content, status, userID)
}

// Put 处理 PUT 请求
func (h *Handler) Put(w http.ResponseWriter, r *http.Request) {
	// 从上下文获取用户
	user := r.Context().Value("user").(model.User)

	// 解析请求体
	var requestBody map[string]interface{}
	if err := json.NewDecoder(r.Body).Decode(&requestBody); err != nil {
		respondWithError(w, http.StatusBadRequest, "Invalid request body")
		return
	}

	// 获取表名和ID
	table, ok := requestBody["table"].(string)
	if !ok || table == "" {
		respondWithError(w, http.StatusBadRequest, "Table name is required")
		return
	}

	id, ok := requestBody["id"].(float64)
	if !ok || id == 0 {
		respondWithError(w, http.StatusBadRequest, "ID is required")
		return
	}

	// 验证表级权限
	verifier := middleware.APIJSONVerifier{}
	if !verifier.Verify(table, "PUT", user.Role) {
		respondWithError(w, http.StatusForbidden, "Insufficient permissions")
		return
	}

	// 处理不同表的更新逻辑
	var result sql.Result
	var err error

	switch table {
	case "User":
		result, err = h.updateUser(user, int(id), requestBody)
	case "Article":
		result, err = h.updateArticle(user, int(id), requestBody)
	default:
		respondWithError(w, http.StatusBadRequest, "Unsupported table")
		return
	}

	if err != nil {
		respondWithError(w, http.StatusInternalServerError, err.Error())
		return
	}

	rowsAffected, err := result.RowsAffected()
	if err != nil {
		respondWithError(w, http.StatusInternalServerError, err.Error())
		return
	}

	respondWithJSON(w, http.StatusOK, Response{
		Code:    http.StatusOK,
		Message: "updated",
		Data:    map[string]int64{"rows_affected": rowsAffected},
	})
}

// updateUser 处理用户更新
func (h *Handler) updateUser(user model.User, id int, data map[string]interface{}) (sql.Result, error) {
	// 检查权限 - 只有管理员或用户自己可以更新
	if user.Role < model.ADMIN && user.ID != id {
		return nil, errors.New("can only update your own profile")
	}

	// 构建更新语句
	var updates []string
	var args []interface{}

	if name, ok := data["name"].(string); ok && name != "" {
		updates = append(updates, "name = ?")
		args = append(args, name)
	}

	if role, ok := data["role"].(string); ok && role != "" {
		// 只有管理员可以更新角色
		if user.Role < model.ADMIN {
			return nil, errors.New("only admin can change roles")
		}
		updates = append(updates, "role = ?")
		args = append(args, role)
	}

	if len(updates) == 0 {
		return nil, errors.New("no fields to update")
	}

	query := "UPDATE User SET " + strings.Join(updates, ", ") + " WHERE id = ?"
	args = append(args, id)

	return h.DB.Exec(query, args...)
}

// updateArticle 处理文章更新
func (h *Handler) updateArticle(user model.User, id int, data map[string]interface{}) (sql.Result, error) {
	// 检查权限 - 只有管理员或文章作者可以更新
	var authorID int
	err := h.DB.QueryRow("SELECT user_id FROM Article WHERE id = ?", id).Scan(&authorID)
	if err != nil {
		return nil, err
	}

	if user.Role < model.ADMIN && user.ID != authorID {
		return nil, errors.New("can only update your own articles")
	}

	// 构建更新语句
	var updates []string
	var args []interface{}

	if title, ok := data["title"].(string); ok && title != "" {
		updates = append(updates, "title = ?")
		args = append(args, title)
	}

	if content, ok := data["content"].(string); ok && content != "" {
		updates = append(updates, "content = ?")
		args = append(args, content)
	}

	if status, ok := data["status"].(string); ok && status != "" {
		updates = append(updates, "status = ?")
		args = append(args, status)
	}

	if len(updates) == 0 {
		return nil, errors.New("no fields to update")
	}

	query := "UPDATE Article SET " + strings.Join(updates, ", ") + " WHERE id = ?"
	args = append(args, id)

	return h.DB.Exec(query, args...)
}

// Delete 处理 DELETE 请求
func (h *Handler) Delete(w http.ResponseWriter, r *http.Request) {
	// 从上下文获取用户
	user := r.Context().Value("user").(model.User)

	// 解析请求参数
	table := r.URL.Query().Get("table")
	if table == "" {
		respondWithError(w, http.StatusBadRequest, "Table name is required")
		return
	}

	idStr := r.URL.Query().Get("id")
	id, err := strconv.Atoi(idStr)
	if err != nil || id == 0 {
		respondWithError(w, http.StatusBadRequest, "Valid ID is required")
		return
	}

	// 验证表级权限
	verifier := middleware.APIJSONVerifier{}
	if !verifier.Verify(table, "DELETE", user.Role) {
		respondWithError(w, http.StatusForbidden, "Insufficient permissions")
		return
	}

	// 处理不同表的删除逻辑
	var result sql.Result

	switch table {
	case "User":
		// 只有管理员可以删除用户
		if user.Role < model.ADMIN {
			respondWithError(w, http.StatusForbidden, "Only admin can delete users")
			return
		}
		result, err = h.DB.Exec("DELETE FROM User WHERE id = ?", id)
	case "Article":
		// 检查文章作者
		var authorID int
		err = h.DB.QueryRow("SELECT user_id FROM Article WHERE id = ?", id).Scan(&authorID)
		if err != nil {
			respondWithError(w, http.StatusInternalServerError, err.Error())
			return
		}
		// 只有管理员或作者可以删除
		if user.Role < model.ADMIN && user.ID != authorID {
			respondWithError(w, http.StatusForbidden, "Can only delete your own articles")
			return
		}
		result, err = h.DB.Exec("DELETE FROM Article WHERE id = ?", id)
	default:
		respondWithError(w, http.StatusBadRequest, "Unsupported table")
		return
	}

	if err != nil {
		respondWithError(w, http.StatusInternalServerError, err.Error())
		return
	}

	rowsAffected, err := result.RowsAffected()
	if err != nil {
		respondWithError(w, http.StatusInternalServerError, err.Error())
		return
	}

	respondWithJSON(w, http.StatusOK, Response{
		Code:    http.StatusOK,
		Message: "deleted",
		Data:    map[string]int64{"rows_affected": rowsAffected},
	})
}

// respondWithError 返回错误响应
func respondWithError(w http.ResponseWriter, code int, message string) {
	respondWithJSON(w, code, Response{
		Code:    code,
		Message: message,
	})
}

// respondWithJSON 返回JSON响应
func respondWithJSON(w http.ResponseWriter, code int, payload interface{}) {
	w.Header().Set("Content-Type", "application/json")
	w.WriteHeader(code)
	json.NewEncoder(w).Encode(payload)
}
